#include "gitlblockevtdispatcher.h"
#include "gitliomsg.h"
GitlBlockEvtDispatcher::GitlBlockEvtDispatcher(QList<GitlModual*>* pcModuals)
{
    m_pcModuals = pcModuals;
    m_iMaxEvtInQue = 10;
    m_cEventQueue.clear();
}

GitlBlockEvtDispatcher::~GitlBlockEvtDispatcher()
{
    m_cEventQueue.clear();
}


/*! send event to event bus
  */
void GitlBlockEvtDispatcher::postEvent(GitlEvent* pcEvt)
{
    m_cEvtQueLocker.lock();

    int iQueLength = m_cEventQueue.size();
    if( iQueLength >= 10 )
    {
        GitlIOMsg::getInstance()->msgOut(QString("Too Many Events (%1) In Queue, Please Wait...").arg(iQueLength));
        m_cEvtQueNotFull.wait(&m_cEvtQueLocker);
    }

    //add to event queue
    m_cEventQueue.push_back(*pcEvt);

    m_cEvtQueNotEmpty.wakeAll();
    m_cEvtQueLocker.unlock();

}

/*!
 * \brief scan the event queue and deal with the event
 */
void GitlBlockEvtDispatcher::run()
{
    forever {
        m_cEvtQueLocker.lock();
        /*empty, wait*/
        if( m_cEventQueue.isEmpty() )
        {
            m_cEvtQueNotEmpty.wait(&m_cEvtQueLocker);
        }

        GitlEvent cEvt = m_cEventQueue.front();
        m_cEventQueue.pop_front();

        m_cEvtQueNotFull.wakeAll();
        m_cEvtQueLocker.unlock();

        /// notify moduals
        for(int iModualCount = 0; iModualCount < m_pcModuals->size(); iModualCount++ )
        {
            if( cEvt.getEvtName() == "*" || m_pcModuals->at(iModualCount)->isListenToEvt(cEvt.getEvtName()) )
            {
                GitlModual* pModual = m_pcModuals->at(iModualCount);
                if( pModual->detonate(&cEvt) )
                {
                    GitlIOMsg::getInstance()->msgOut(QString("Modual %1 Success in Processing %2 Event.").arg(pModual->getModualName()).arg(cEvt.getEvtName()), GITL_MSG_DEBUG );
                }
                else
                {
                    GitlIOMsg::getInstance()->msgOut(QString("Modual %1 Fail in Processing %2 Event.").arg(pModual->getModualName()).arg(cEvt.getEvtName()), GITL_MSG_WARNING );
                }
            }

        }

    }
}
